package template;


import java.sql.Date;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

import net.java.ao.DatabaseProvider;
import net.java.ao.EntityManager;

import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.*;
import org.apache.wicket.markup.repeater.RepeatingView;

/**
 * Page that adds a template border for layout.
 * 
 */
public class ViewCalendars extends Restricted
{
    /**
     * Constructor
     */
    public ViewCalendars() {
    	//constructs from Restricted class
    	super();
    	
    	//creates instance of EntityManager that handles database
    	EntityManager manager = new EntityManager(DatabaseProvider.getInstance(
				"jdbc:hsqldb:mem:basic-ao", null, null));
    	
    	//defines the user in the current session
    	Person user = (Person)_session.getUser();
    	
    	//creates a calendar to retrieve current month/day to construct calendar view
        GregorianCalendar calendar = new GregorianCalendar();
        int original_month = calendar.get(java.util.Calendar.MONTH);
        int original_day = calendar.get(java.util.Calendar.DAY_OF_MONTH);
        calendar.set(java.util.Calendar.DAY_OF_MONTH, 1);
        
        //adds label to layout that shows the name of the month displayed 
        _layout.add(new Label("calendar_name", calendar.getDisplayName(java.util.Calendar.MONTH, 2, Locale.US)));
        
        //rolls calendar back to first day of week to determine first day of month in week
        while(calendar.get(java.util.Calendar.DAY_OF_WEEK) != 1){
        	calendar.roll(java.util.Calendar.DAY_OF_WEEK, false);
        }
        
        //generates the calendar view on the ViewCalendar page
        RepeatingView days = new RepeatingView("day_div");
        _layout.add(days); 
        for(int i=0; i<36; i++) {
            WebMarkupContainer day = new WebMarkupContainer(days.newChildId());
            days.add(day);
            java.util.Calendar new_cal = (java.util.Calendar) calendar.clone();
            calendar.roll(java.util.Calendar.DAY_OF_YEAR, true);

            day.add(new Label("date", String.valueOf(calendar.get(java.util.Calendar.DAY_OF_MONTH))));
            String klass = "cell";
            if (calendar.get(java.util.Calendar.MONTH) == original_month){
            	klass += " current";
              	if (calendar.get(java.util.Calendar.DAY_OF_MONTH) == original_day){
              		klass += " today";
                }
            }else{
            	klass += " unscoped";
            }
            if (i % 7 == 0){
            	klass += " clear-left";
            }

            day.add(new SimpleAttributeModifier("class", klass)); 
            
            day.setMarkupId("day_" + Integer.toString(calendar.get(java.util.Calendar.MONTH))+ '_' + Integer.toString(calendar.get(java.util.Calendar.DAY_OF_MONTH)));
            day.setOutputMarkupId(true);
            
            new_cal.set(calendar.get(java.util.Calendar.YEAR), calendar.get(java.util.Calendar.MONTH), calendar.get(java.util.Calendar.DAY_OF_MONTH), 0, 0, 0);
            String lower_bound = new Timestamp(new_cal.getTimeInMillis()).toString();
            
            new_cal.set(calendar.get(java.util.Calendar.YEAR), calendar.get(java.util.Calendar.MONTH), calendar.get(java.util.Calendar.DAY_OF_MONTH), 23, 59, 59);
            String upper_bound = new Timestamp(new_cal.getTimeInMillis()).toString();
                         
            try {
            	RepeatingView entries = new RepeatingView("events");
                day.add(entries);
            	
            	Event[] events = manager.findWithSQL(Event.class, "id","SELECT event.* FROM event INNER JOIN eventsToCalendars ON eventsToCalendars.eventID = event.id INNER JOIN calendar ON calendar.id = eventsToCalendars.calendarID WHERE (calendar.creatorID = ? AND event.startDate >= ? AND event.startDate < ?) ORDER BY event.startDate",user.getID(),lower_bound,upper_bound);
        		
        		for(int e=0; e<events.length; e++) {
        			Event event = events[e];
        			String event_id = "event_" + Integer.toString(event.getID());
        			
        			WebMarkupContainer event_row = new WebMarkupContainer(days.newChildId());
        			entries.add(event_row);
        			Label link = new Label("name", event.getName());
        			event_row.add(link);
        			
        			link.add(new SimpleAttributeModifier("rel", event_id));
        			
        			WebMarkupContainer details = new WebMarkupContainer("details");
        			event_row.add(details);
        			
        			details.setMarkupId(event_id);
        			details.setOutputMarkupId(true);
        				
	        		    SimpleDateFormat format = new SimpleDateFormat("K:mm a");
        				details.add(new Label("startDate", format.format(event.getStartDate())));
        				
        				SimpleDateFormat end_format = new SimpleDateFormat("K:mm a (EEE, MMM d)");
        				details.add(new Label("endDate", end_format.format(event.getEndDate())));
        				
        				details.add(new Label("desc", event.getDescription()));
        		}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
            

        }
    }
}